function makeJSONRequest() {    
  var prefs = new gadgets.Prefs();
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
  var url = 'http://img.livetv.ru/rss/gadget_' + prefs.getMsg('locale') + '.xml';
  gadgets.io.makeRequest(url, response, params);
};

function createFilter(items){
	var html = '<div id="filter">';
	items.sort( function( a , b ){
	  return a.id - b.id;
	});
	
	for(var i = 0; i < items.length; i++){
		if(items[i] !== undefined){
			html += '<div class="filter_item" id="sport_' + items[i].id + '">'
			html += '<img title="' + items[i].sport + '" alt="' + items[i].sport + '" width="34" height="34" src="http://img.livetv.ru/img/sport/' + items[i].id + '.gif" style="cursor: pointer;" class="filter_image">';
			html += '</div>';
		}
	}
	
	html += '</div>';
	return html;
}

function response(obj) { 

  if (!obj.data) {
    try { 
      obj.data = eval("foo=" + obj.text); 
    } 
    catch(e) {}
  }
	
  var filter = new Array();		
  var prefs = new gadgets.Prefs();
  var html = "<table>";
  var cnt = 0;
  
  if(obj.data){ 
    var jsondata = obj.data;        
    var dt_cur = new Date();
  
    for (var i = 0; i < jsondata.length ; i++){   
      var msec_start = parseInt(jsondata[i].datetime) * 1000;
      var dt_start   = new Date(msec_start);
      var dt_end     = new Date(msec_start + parseInt(jsondata[i].actiontime) * 60 * 1000);
      
      if(dt_cur < dt_end){    
        html += '<tr class="event sport_' + jsondata[i].sport_id + '"><td width="30">';
        html += '<img src="http://img.livetv.ru/img/icons/' + jsondata[i].icon + '.gif">';
        html += '</td><td>';
              
        html += '<a href="' + prefs.getMsg('title_url') + 'eventinfo/' + jsondata[i].id + '/" target="_blank">' + jsondata[i].title + '</a>'; 
        if(dt_cur > dt_start){
          html += '&nbsp;<img src="http://img.livetv.ru/img/live.gif">';
        }
        html += '<br/>';
        html += '<span class="gray">' + jsondata[i].sport + '. ' + jsondata[i].competition + '<br>' + dt_start.format('isoDate') + ' ' + dt_start.format('isoTime') + '</span>';
        html += '</td></tr>';
		
		if(filter[jsondata[i].sport_id] === undefined){
			filter[jsondata[i].sport_id] = {"id": jsondata[i].sport_id, "sport": jsondata[i].sport};
		}
		
        cnt++;
      } 
    }
  }
  
  if(!cnt){
    html += '<tr><td>' + prefs.getMsg('error_cnt') +'</td></tr>';
  }
  
  html += '</table>';   
  document.getElementById('content_div').innerHTML = createFilter(filter) + '<div class="clearfix"></div>' + html;
  
  $('.filter_item').click(function() {
	  $('.event').hide();
	  $('.' + this.id).show();
	});
 };
     
gadgets.util.registerOnLoadHandler(makeJSONRequest);